﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Web;

namespace WebMsg
{
    public class BulkSms : WebMsg
    {
        // BulkSms setting constants
        private const String origin = "i";
        private const String tracking = "0";
        private const String returnMID = "1";

        public BulkSms()
            : base()
        {
            this.messageURL = @"https://secure.ai.com.au/bulksms/httpsend.php?";
            this.balanceURL = @"https://secure.ai.com.au/bulksms/httpcreditcheck.php?";
            this.CustomFrom = true;
        }

        protected override void AddResults()
        {
            Results.Add("success", ResultCodes.ErrorTimeout);
        }

        protected override String SendMessage(Sms message)
        {
            String strPost = this.Build(message);
            strPost = HttpUtility.UrlPathEncode(strPost);
            Uri address = new Uri(messageURL + strPost);

            return SendMessage(message, address);
        }

        // Builds the message
        protected String Build(Sms message)
        {
            if (null == message)
                throw new ArgumentNullException("message");

            StringBuilder result = new StringBuilder();
            result.Append("usr=");
            result.Append(User);
            result.Append("&pass=");
            result.Append(Pass);
            result.Append("&to=");
            result.Append(message.To.Number);
            result.Append("&mess=");
            result.Append(HttpUtility.UrlPathEncode(message.Body));
            result.Append("&from=");
            result.Append(message.From.Number);
            result.Append("&origin=");
            result.Append(origin);
            result.Append("&tracking=");
            result.Append(tracking);
            result.Append("&longsms=");
            result.Append(message.LongMessage);
            result.Append("&returnMID=");
            result.Append(returnMID);
            return result.ToString();
        }

        protected override ResultCodes ParseResult(String rawResult)
        {
            if(String.IsNullOrWhiteSpace(rawResult))
                throw new ArgumentNullException("rawResult");

            String result = rawResult.Substring(0, 7);

            return base.ParseResult(result);
        }

        public override String GetCreditsRemaining()
        {
            StringBuilder strPost = new StringBuilder(balanceURL);
            strPost.Append("usr=");
            strPost.Append(User);
            strPost.Append("&pass=");
            strPost.Append(Pass);

            return GetCreditsRemainingRaw(strPost.ToString());
        }
    }
}
